import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kefu_plugin/flutter_kefu_plugin.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_picker/image_picker.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController _contentController = new TextEditingController();
  String _platformVersion = 'Unknown';
  bool initResult = false;
  bool _permissionReady = false;
  String _enterpriseWelcome = '';
  File _imageFile;

  ///在线客服appkey
  static const KEFU_APPKEY = '1442200515068511#kefuchannelapp81157';

  ///在线客服租户id
  static const KEFU_TENANT_ID = '81157';

  ///在线客服IM服务号
  static const KEFU_IM_SERVICE_ID = 'kefuchannelimid_073465';

  String username = 'HX_34430';
  String password = 'f52371013572ebea804e74921eaefe73';

  @override
  void initState() {
    super.initState();
    initPlatformState();
    initEasemobKeFuSdk();
    initEventChannelListener();
  }

  void initEventChannelListener() {
    EventChannel('flutter_kefu_plugin_event_channel')
        .receiveBroadcastStream()
        .listen((data) {
      print(data);
    }, onDone: () {}, onError: (args) {});
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await FlutterKefuPlugin.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
    _permissionReady = await _checkPermission();
  }

  Future<void> initEasemobKeFuSdk() async {
    bool flag = await FlutterKefuPlugin.init(
      appKey: KEFU_APPKEY,
      tenantId: KEFU_TENANT_ID,
      logEnable: true,
    );
    if (!mounted) {
      return;
    }
    setState(() {
      initResult = flag;
    });
  }

  Future<void> loginHx(String username, String password) async {
    if (_permissionReady) {
      bool result =
          await FlutterKefuPlugin.login(username: username, password: password);
      if (result) {
        print('login success');
      }
    } else {
      _checkPermission().then((hasGranted) {
        setState(() {
          _permissionReady = hasGranted;
        });
      });
    }
  }

  Future<void> sendTextMessage() async {
    String content = _contentController.text;
    if (content.isEmpty) {
      print('Please enter what you want to say');
      return;
    }
    bool flag = await FlutterKefuPlugin.sendTextMessage(
        content: content, toChatUsername: KEFU_IM_SERVICE_ID);
    if (!mounted) {
      return;
    }
    setState(() {
      if (flag) {
        FocusScope.of(context).requestFocus(FocusNode());
        _contentController.text = '';
      }
    });
  }

  Future<void> getConversationMessages() async {
    String message = await FlutterKefuPlugin.getConversationMessages(
        toChatUsername: KEFU_IM_SERVICE_ID);
    print(message);
  }

  Future<bool> _checkPermission() async {
    if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  Future<void> addMessageListener() async {
    String message = await FlutterKefuPlugin.addMessageListener();
    print(message);
    if (message.isEmpty) {
      return;
    }
  }

  Future<void> getEnterpriseWelcome() async {
    String enterpriseWelcome = await FlutterKefuPlugin.getEnterpriseWelcome();
    if (!mounted) {
      return;
    }
    setState(() {
      _enterpriseWelcome = enterpriseWelcome;
    });
  }

  Future getImage(bool fromAlbum) async {
    var image = await ImagePicker.pickImage(
        source: fromAlbum ? ImageSource.gallery : ImageSource.camera);
    setState(() {
      if (image != null) {
        _imageFile = image;
        sendImageMessage();
      }
    });
  }

  Future<void> sendImageMessage() async {
    bool result = await FlutterKefuPlugin.sendImageMessage(
        filePath: _imageFile.path,
        toChatUsername: KEFU_IM_SERVICE_ID,
        sendOriginalImage: true);
    if (!mounted) {
      return;
    }
    print('==============sendImageMessage result:=======' + result.toString());
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        backgroundColor: Color(0xFF08172A),
        appBar: AppBar(
          title: const Text(
            'Plugin example app',
            style: TextStyle(
              color: Colors.white,
              fontSize: 12,
            ),
          ),
        ),
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  'Running on: $_platformVersion\n',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                  ),
                ),
                RaisedButton(
                  onPressed: () {
                    loginHx(username, password);
                  },
                  child: Text('登录'),
                ),
                Container(
                  height: 50,
                  margin: EdgeInsets.fromLTRB(
                    12,
                    5,
                    0,
                    6,
                  ),
                  decoration: BoxDecoration(
                    color: Color(0x19FFFFFF),
                    borderRadius: BorderRadius.all(Radius.circular(4)),
                  ),
                  child: TextField(
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                    ),
                    maxLines: 1,
                    maxLength: 150,
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.send,
                    onEditingComplete: () {
                      sendTextMessage();
                    },
                    decoration: InputDecoration(
                      counterText: '',
                      hintText: 'Please enter what you want to say',
                      hintStyle: TextStyle(color: Colors.white60, fontSize: 12),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide.none,
                      ),
                      contentPadding: EdgeInsets.fromLTRB(12, 13, 12, 13),
                    ),
                    controller: _contentController,
                  ),
                ),
                RaisedButton(
                  onPressed: () {
                    sendTextMessage();
                  },
                  child: Text('发送消息'),
                ),
                RaisedButton(
                  onPressed: () {
                    getConversationMessages();
                  },
                  child: Text('获取聊天记录'),
                ),
                RaisedButton(
                  onPressed: () {
                    addMessageListener();
                  },
                  child: Text('添加消息监听'),
                ),
                RaisedButton(
                  onPressed: () {
                    _clickSendImage();
                  },
                  child: Text('发送图片'),
                ),
                RaisedButton(
                  onPressed: () {
                    deleteConversation();
                  },
                  child: Text('删除会话'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _clickSendImage() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          width: MediaQuery.of(context).size.width,
          height: 146,
          color: Color(0xFF0C5E96),
          child: Column(
            children: <Widget>[
              ///从相册选择
              Expanded(
                flex: 1,
                child: InkWell(
                  onTap: () {
                    Navigator.pop(context);
                    getImage(true);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: Text(
                      '从相册选择',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                      ),
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
              Divider(
                color: Colors.black12,
                height: 1,
              ),

              ///拍照
              Expanded(
                flex: 1,
                child: InkWell(
                  onTap: () {
                    Navigator.pop(context);
                    getImage(false);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: Text(
                      '拍照',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                      ),
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
              Divider(
                color: Colors.black12,
                height: 1,
              ),

              ///取消
              Expanded(
                flex: 1,
                child: InkWell(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                      ),
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  void deleteConversation() async {
    bool result = await FlutterKefuPlugin.deleteConversation(
        username: KEFU_IM_SERVICE_ID, deleteMessages: true);
    print(
        '============================delete conversation:' + result.toString());
  }
}
